package com.wzd.shoppingService.utils;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description 用户IP工具类
 * @Author ruan
 * @Date 2019-11-26 14:01
 **/
public class IpUtils {

    /**
     * @param request
     * @Description 用户真实IP获取
     * @Date 2019-11-26 13:36
     */
    public static String getIpAddr(HttpServletRequest request) {

        String ip = request.getHeader("X-Forwarded-For");
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }
}
